<?php
require_once './vendor/autoload.php';
//非核心代码
$api_uid = 1;//自己业务里的用户个人ID
$chat_id = 1;//自己业务里的用户会话ID
//初始化配置文件
$config_file = __DIR__ . "/config.json";
$config_data = json_decode(file_get_contents($config_file), true);
$app_id = $config_data['app_id'];
$app_key = $config_data['app_key'];
$app_secret = $config_data['app_secret'];
//构造请求数据
$api_host = "spark-api.xf-yun.com";
$api_path = "/v1.1/chat";
$api_date = gmdate(DATE_RFC7231);
$tmp_base = "host: $api_host\ndate: $api_date\nGET $api_path HTTP/1.1";
$tmp_sha = hash_hmac("sha256", $tmp_base, $app_secret, true);
$tmp_sign = base64_encode($tmp_sha);
$tmp_auth = "api_key=\"$app_key\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"$tmp_sign\"";
$api_auth = base64_encode($tmp_auth);
$api_get = http_build_query(["authorization" => $api_auth, "date" => $api_date, "host" => $api_host]);
$api_url = "wss://{$api_host}{$api_path}?{$api_get}";
//记录用户聊天历史
$history = [];
//循环对话流程控制
jump:
echo "用户提问：";
echo PHP_EOL;
$api_content = trim(fgets(STDIN));
echo PHP_EOL;
//记录用户聊天历史
$history[] = ["role" => "user", "content" => $api_content];
$api_data = json_encode([
    "header" => [
        "app_id" => $app_id,
        "uid" => "$api_uid",
    ],
    "parameter" => [
        "chat" => [
            "domain" => "general",
            "temperature" => 0.5,
            "max_tokens" => 4096,
            "top_k" => 4,
            "chat_id" => "{$api_uid}-{$chat_id}",
        ],
    ],
    "payload" => [
        "message" => [
            //记录用户聊天历史(AI只记住最后4次会话的内容)
            "text" => array_slice($history, -4),
        ],
    ],
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
//发送会话请求
try {
    $request = new WebSocket\Client($api_url);
    $request->send($api_data);
} catch (\Exception $e) {
    echo $e->getMessage();
    echo PHP_EOL;
}
//AI会分多次回复，通过$content对回复进行拼接，status == 2 是对当前对话的最后一次拼接
$content = "";
while (true) {
    $response = $request->receive();
    $resp = json_decode($response, true);
    $code = $resp["header"]["code"];
    if ($resp["header"]["code"] == 0) {
        $content .= $resp['payload']['choices']['text'][0]['content'];
        if ($resp["header"]["status"] === 2) {
            echo "讯飞回复：";
            echo PHP_EOL;
            echo $content;
            echo PHP_EOL;
            //记录AI聊天历史
            $history[] = ["role" => "assistant", "content" => $content];
            echo PHP_EOL;
            echo PHP_EOL;
            //回到请求发起位置
            goto jump;
        }
    } else {
        echo "讯飞报错：";
        echo PHP_EOL;
        echo $resp["header"]["message"];
        echo PHP_EOL;
        break;
    }
}
